package com.spring.boot.controller;

import com.spring.boot.entity.server.CommonResult;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 刘骄阳
 * 2021-07-12 16:06
 */
@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping("/add")
    public CommonResult add() {
        return new CommonResult().success(SecurityContextHolder.getContext().getAuthentication());

    }

    @PreAuthorize("hasAnyAuthority('2','3')")
    @GetMapping("/insert")
    public CommonResult insert() {
        return new CommonResult().success(SecurityContextHolder.getContext().getAuthentication());

    }

    @GetMapping("/index")
    public CommonResult index() {
        return new CommonResult().success(SecurityContextHolder.getContext().getAuthentication());
    }


    @GetMapping("/hello")
    public CommonResult hello() {
        return new CommonResult().success(SecurityContextHolder.getContext().getAuthentication());
    }

    /**
     * 需要具有  ROLE_管理员  权限才能访问
     *
     * @return 上下文中的用户信息
     */
    @Secured("ROLE_管理员")
    @GetMapping("/root")
    public CommonResult root() {
        return new CommonResult().success(SecurityContextHolder.getContext().getAuthentication());
    }

    @GetMapping("/getToken")
    public CommonResult getToken(HttpServletRequest request) {
        Object token = request.getAttribute("token");
        if (token != null) {
            System.out.println(token);
            return new CommonResult().success(token);
        }
        return new CommonResult().failed("token格式错误");
    }


}
